package com.pantech.app.call_log_enabler;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.location.LocationManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.SystemClock;
import android.provider.Settings;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.content.res.Resources;
import android.graphics.Color;
import android.support.v4.app.FragmentActivity;
import android.text.InputFilter;
import android.text.InputType;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

public class MainActivity extends FragmentActivity {
	
	CheckBox enable_checkbox;
	Button clean_button;
	CheckBox pcap_checkbox;
	CheckBox udp_checkbox;
	CheckBox ddms_log_checkbox;
	CheckBox pcap_log_checkbox;
	CheckBox radio_log_checkbox;
	CheckBox remove_buffer_checkbox;
	CheckBox use_gps_checkbox;
	CheckBox use_network_location_checkbox;
	Button clean_appLog_button;
	Button location_refreshing_time_text;
	
	private final String LOG_TAG = "LogApp";
	private final String CALL_LOG = "calllog";
	private final String APP_LOG = "applog";
    
    static final String Log_path = "/calllog_app/";
    static final String Log_path_VT = "/calllog/";
    static final String Folder_path = Environment.getExternalStorageDirectory().getPath();
    
    private static SharedPreferences VTPref = null;
    public static boolean isLogEnabled = false;
    public static boolean isLogEnabled_applog = false;
    public static boolean isEngBinary = "eng".equals(Build.TYPE);
    public static Toast m_Toast = null;
    
    public static boolean isActivityActive = false;
    private ContentResolver cr;
    private UserSharedPreference mUserSharedPreference;
    
    public final String pref_CALLLOG_ONGOING = UserSharedPreference.pref_CALLLOG_ONGOING;
    public final String pref_UDP_CHECKED = UserSharedPreference.pref_UDP_CHECKED;
    public final String pref_DDMS_CHECKED = UserSharedPreference.pref_DDMS_CHECKED;
    public final String pref_PCAP_CHECKED = UserSharedPreference.pref_PCAP_CHECKED;
    public final String pref_RADIO_CHECKED = UserSharedPreference.pref_RADIO_CHECKED;
    public final String pref_REMOVE_BUFFER_CHECKED = UserSharedPreference.pref_REMOVE_BUFFER_CHECKED;
    public final String pref_USE_APPLOG_IN_USERMODE = UserSharedPreference.pref_USE_APPLOG_IN_USERMODE;
    public final String pref_USE_GPS_CHECKED = UserSharedPreference.pref_USE_GPS_CHECKED;
    public final String pref_USE_NETWORK_LOCATION_CHECKED = UserSharedPreference.pref_USE_NETWORK_LOCATION_CHECKED;
    public final String pref_LOCATION_REFRESHING_TIME = UserSharedPreference.pref_LOCATION_REFRESHING_TIME;
    public final String pref_IS_BUSYBOX_CHECKED = UserSharedPreference.pref_IS_BUSYBOX_CHECKED;
    public final String pref_IS_FIELDTEST_MODE = UserSharedPreference.pref_IS_FIELDTEST_MODE;
    public final String pref_IS_BUSYBOX_EXIST = UserSharedPreference.pref_IS_BUSYBOX_EXIST;
    
    public final int first_MENU = 1;
    public final int second_MENU = 2;
    public final int third_MENU = 3;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		cr = getContentResolver();
		mUserSharedPreference = new UserSharedPreference(getApplicationContext());
		
		enable_checkbox = (CheckBox)findViewById(R.id.enable_button);
		enable_checkbox.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(mUserSharedPreference.getBoolean_pref(UserSharedPreference.pref_CALLLOG_ONGOING)&&!isLogEnabled) {
					ShowToast("Disable Log on this app!!", Toast.LENGTH_SHORT);
					ChangeCheckboxStatus(enable_checkbox, false);
				}else {
					Intent intent;
					intent = new Intent("com.pantech.action.CALL_LOG_ENABLE");
			        sendBroadcast(intent);
			        ChangeCheckboxStatus(enable_checkbox, !isLogEnabled);
			        ChangeNotification(CALL_LOG, !isLogEnabled);
			        isLogEnabled=!isLogEnabled;
			        if(isLogEnabled == false) {
			        	sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
	                            + (new File(String.format("" + Folder_path + Log_path_VT))))));
			        }
				}
			}
        });
		
		clean_button = (Button)findViewById(R.id.clean_button);
		clean_button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(MainActivity.this).setTitle("Clean All Logs?")
				.setMessage("To clean all logs, Click OK")
				.setPositiveButton("OK", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						Intent intent;
						intent = new Intent("com.pantech.action.CALL_LOG_REMOVE");
				        sendBroadcast(intent);
				        sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
	                            + (new File(String.format("" + Folder_path + Log_path_VT))))));
					}
				})
				.setNegativeButton("No", new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();
					}
				})
				.create().show();
			}
        });

		if(getApplicationContext().checkCallingOrSelfPermission("android.permission.READ_LOGS")
		        != PackageManager.PERMISSION_GRANTED) {
			new AlertDialog.Builder(this)
			.setTitle("Doesn't have READ_LOGS permission!!")
			.setMessage("You installed app with wrong signing.\nGet Signed or Give permission!!")
			.setPositiveButton("Close this app", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
					dialog.dismiss();
					finish();
				}
			})
			.setNegativeButton("Use without permission", new DialogInterface.OnClickListener() {
				@Override
				public void onClick(DialogInterface dialog, int which) {
				}
			}).create().show();
			pcap_checkbox.setEnabled(false);
	    }
		
		pcap_checkbox = (CheckBox)findViewById(R.id.pcap_button);
		pcap_checkbox.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!getBoolean_pref(pref_CALLLOG_ONGOING)) {
					if(!isLogEnabled) {
						if(!getBoolean_pref(pref_DDMS_CHECKED) && !getBoolean_pref(pref_PCAP_CHECKED) && !getBoolean_pref(pref_RADIO_CHECKED)) {
							ChangeCheckboxStatus(pcap_checkbox, false);
							ShowToast("No logs has been checked", Toast.LENGTH_SHORT);
						} else {
							startLogProcess();
							ChangeCheckboxStatus(pcap_checkbox, true);
							ChangeNotification(APP_LOG, true);
		                	requestLocationUpdate();
						}
					} else {
						ChangeCheckboxStatus(pcap_checkbox, false);
						ShowToast("Disable Log on Hidden menu!!", Toast.LENGTH_SHORT);
					}
		        } else if(getBoolean_pref(pref_CALLLOG_ONGOING)) {   
		        	ChangeCheckboxStatus(pcap_checkbox, false);	//should be : before killLogprocess()
		        	killLogprocess();
		        	setBoolean_pref(pref_CALLLOG_ONGOING, false);
		        	removeLocationUpdate();
		        	ChangeNotification(APP_LOG, false);
		        	
		        	//File name change dialog
		        	final EditText input = new EditText(MainActivity.this);
		        	new AlertDialog.Builder(MainActivity.this)
		        	.setTitle("Add String to file name")
		    		.setView(input)
		    		.setCancelable(false)
		    		.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		    			public void onClick(DialogInterface dialog, int whichButton) {
		    				String value = input.getText().toString();
		    				if(!value.toString().equals("")) {
		    					reNameFile(new File(String.format(ProcessService.arg_ddms)), new File(String.format(ProcessService.fileName + "_" + value.toString() + ".txt")));
		        				reNameFile(new File(String.format(ProcessService.arg_pcap)), new File(String.format(ProcessService.fileName + "_" + value.toString() + ".pcap")));
		        				reNameFile(new File(String.format(ProcessService.arg_radio)), new File(String.format(ProcessService.fileName + "_radio" +"_" + value.toString() + ".txt")));
		    				}
		    			}
		    		}).create().show();
		        	//File name change dialog - end
		        }
			}
        });
		
		ddms_log_checkbox = (CheckBox)findViewById(R.id.ddms_log_button);
		CheckBoxClickListenerGenerater(ddms_log_checkbox, pref_DDMS_CHECKED);
		
		pcap_log_checkbox = (CheckBox)findViewById(R.id.pcap_log_button);
		CheckBoxClickListenerGenerater(pcap_log_checkbox, pref_PCAP_CHECKED);
		
		radio_log_checkbox = (CheckBox)findViewById(R.id.radio_log_button);
		CheckBoxClickListenerGenerater(radio_log_checkbox, pref_RADIO_CHECKED);
		
		udp_checkbox = (CheckBox)findViewById(R.id.udp_button);
		CheckBoxClickListenerGenerater(udp_checkbox, pref_UDP_CHECKED);
		
		remove_buffer_checkbox = (CheckBox)findViewById(R.id.remove_buffer_button);
		remove_buffer_checkbox.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(!getBoolean_pref(pref_REMOVE_BUFFER_CHECKED)) {
					setBoolean_pref(pref_REMOVE_BUFFER_CHECKED, true);
					ChangeCheckboxStatus(remove_buffer_checkbox, true);
		        } else {
		        	setBoolean_pref(pref_REMOVE_BUFFER_CHECKED, false);
		        	ChangeCheckboxStatus(remove_buffer_checkbox, false);
		        }
				
			}
		});
		
		location_refreshing_time_text = (Button)findViewById(R.id.location_refreshing_time_text);
		location_refreshing_time_text.setText(getInt_pref(pref_LOCATION_REFRESHING_TIME) + " Sec refreshing");
		location_refreshing_time_text.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!getBoolean_pref(pref_CALLLOG_ONGOING)) {
					final EditText input = new EditText(MainActivity.this);
					input.setInputType(InputType.TYPE_CLASS_NUMBER);
					input.setText(Integer.toString(getInt_pref(pref_LOCATION_REFRESHING_TIME)));
					input.setSingleLine();
					int maxLength = 5;
					InputFilter[] finterArray = new InputFilter[1];
					finterArray[0] = new InputFilter.LengthFilter(maxLength);
					input.setFilters(finterArray);
					new AlertDialog.Builder(MainActivity.this)
		        	.setTitle("Set Location refreshing time\n(Seconds)")
		        	.setMessage("<Set '0' to refresh\nonce/activity resume>")
		    		.setView(input)
		    		.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
		    			public void onClick(DialogInterface dialog, int whichButton) {
		    				String value = input.getText().toString();
		    				setInt_pref(pref_LOCATION_REFRESHING_TIME, Integer.parseInt(value));
		    				location_refreshing_time_text.setText(getInt_pref(pref_LOCATION_REFRESHING_TIME) + " Sec refreshing");
		    			}
		    		}).create().show();
				} else {
					ShowToast("Call log is onging!!", Toast.LENGTH_SHORT);
				}
				
			}
        });
		
		use_gps_checkbox = (CheckBox)findViewById(R.id.use_gps_button);
		CheckBoxClickListenerGenerater(use_gps_checkbox, pref_USE_GPS_CHECKED);
		
		use_network_location_checkbox = (CheckBox)findViewById(R.id.use_network_location_button);
		CheckBoxClickListenerGenerater(use_network_location_checkbox, pref_USE_NETWORK_LOCATION_CHECKED);
		
		clean_appLog_button = (Button)findViewById(R.id.clean_appLog_button);
		clean_appLog_button.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				if(!getBoolean_pref(pref_CALLLOG_ONGOING)) {
					new AlertDialog.Builder(MainActivity.this).setTitle("Clean All Logs?")
					.setMessage("To clean all logs, Click OK")
					.setPositiveButton("OK", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
						File file = new File(String.format("" + Folder_path + Log_path));
							
			            	if(file.exists()) {
			            		File[] childFileList = file.listFiles();
			            		for(File childFile : childFileList) {
			            			childFile.delete();
			            		}
			            		file.delete();		
			            		
			            		sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
			                            + (new File(String.format("" + Folder_path + Log_path))))));
			            		Log.d(LOG_TAG, "(Make Call log) - Remove Call log folder ");
			            		ShowToast("App Call Log - Removed!!", Toast.LENGTH_SHORT);
			            	} else {
			            		ShowToast("App Call Log - Doesn't exist!!", Toast.LENGTH_SHORT);
			                }
						}
					})
					.setNegativeButton("No", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.cancel();
						}
					})
					.create().show();
				} else {
					ShowToast("Log process is Enabled, Disable Log process", Toast.LENGTH_SHORT);
				}
				
			}
        });
		///////////////////////////////////////test
		
		LinearLayout LL = (LinearLayout)findViewById(R.id.activity_main);
		
		if(isEngBinary) {
			Log.d(LOG_TAG, "Make log pref_IS_BUSYBOX_CHECKED " + getBoolean_pref(pref_IS_BUSYBOX_CHECKED));
			if(getBoolean_pref(pref_IS_BUSYBOX_CHECKED) == false) {
				CopyFileToSDcard(R.raw.busybox, "/system/bin/", "busybox");
				File file = new File(String.format("/system/bin/" + "busybox"));
		    	if(!file.exists()) {
		    		new AlertDialog.Builder(this)
					.setTitle("Copy busybox failed,\nLog process can't be stopped!!")
					.setMessage("Follow below steps\n\nadb remount\nadb shell\nchmod 777 /system/bin\n\nAnd start this app again!!!")
					.setPositiveButton("Close this app", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							dialog.dismiss();
							finish();
						}
					})
					.setNegativeButton("Use without 'busybox'", new DialogInterface.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog, int which) {
							LinearLayout LL = (LinearLayout)findViewById(R.id.activity_main);
							LL.setBackgroundColor(Color.WHITE);
							setBoolean_pref(pref_IS_BUSYBOX_CHECKED, true);
						}
					}).create().show();
		    		
		    		LL.setBackgroundColor(Color.BLACK);
		    	}else {
		    		setBoolean_pref(pref_IS_BUSYBOX_EXIST, true);
		    	}
			}
			LL.removeViewInLayout(findViewById(R.id.usermode_text));
		} else {
			Log.d(LOG_TAG, "Make log > User Build!!");
			
			setBoolean_pref(pref_PCAP_CHECKED, false);
			ChangeCheckboxStatus(pcap_log_checkbox, false);
			pcap_log_checkbox.setEnabled(false);
			
			setBoolean_pref(pref_UDP_CHECKED, false);
			ChangeCheckboxStatus(udp_checkbox, false);
			udp_checkbox.setEnabled(false);
			
//			if(!getBoolean_pref(pref_USE_APPLOG_IN_USERMODE)) {
//				LinearLayout group_applog = (LinearLayout)findViewById(R.id.group_applog);
//				LL.removeViewInLayout(group_applog);
//			}
			
//			LinearLayout group_other_option = (LinearLayout)findViewById(R.id.group_other_option);
//			LL.removeViewInLayout(group_other_option);
			
		}	
	}
	
	public void CheckBoxClickListenerGenerater(final CheckBox checkbox, final String pref) {
		checkbox.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View arg0) {
				if(!getBoolean_pref(pref_CALLLOG_ONGOING)) {
					if(!getBoolean_pref(pref)) {
						setBoolean_pref(pref, true);
						checkedOnClick(pref);
						ChangeCheckboxStatus(checkbox, true);
			        } else {
			        	setBoolean_pref(pref, false);
			        	uncheckedOnClick(pref);
			        	ChangeCheckboxStatus(checkbox, false);
			        }
				} else {
					ChangeCheckboxStatus(checkbox, getBoolean_pref(pref));
					ShowToast("Call log is onging!!", Toast.LENGTH_SHORT);
				}
			}
		});
	}
	
	public void checkedOnClick(String pref) {
	}
	
	public void uncheckedOnClick(String pref) {
		if(pref.equals(pref_USE_GPS_CHECKED)) {
			if(Settings.Secure.isLocationProviderEnabled(cr, LocationManager.GPS_PROVIDER)) Settings.Secure.setLocationProviderEnabled(cr, LocationManager.GPS_PROVIDER, false);
	        if(Settings.Secure.getInt(cr, "assisted_gps_enabled", 1) != 0) Settings.Secure.putInt(cr, "assisted_gps_enabled", 0);
		}else if(pref.equals(pref_USE_NETWORK_LOCATION_CHECKED)) {
			if(Settings.Secure.isLocationProviderEnabled(cr, LocationManager.NETWORK_PROVIDER)) Settings.Secure.setLocationProviderEnabled(cr, LocationManager.NETWORK_PROVIDER, false);
		}
	}
	
	@Override
	protected void onResume() {
		super.onResume();
		
		Context other = null;
		try {
			other = createPackageContext("com.pantech.app.vt", CONTEXT_IGNORE_SECURITY);
			VTPref = other.getSharedPreferences("Preferences.pref", MODE_MULTI_PROCESS);
			isLogEnabled = VTPref.getBoolean("sip_IsCallLogEnabled", false);
		} catch (NameNotFoundException e1) {
			Log.e(LOG_TAG, "Make log > get SharedPreference failed!!");
			e1.printStackTrace();
		}
		
		updateCheckboxStatus();
		ChangeNotification(CALL_LOG, isLogEnabled);
		
		if(getBoolean_pref(pref_CALLLOG_ONGOING) && getInt_pref(pref_LOCATION_REFRESHING_TIME) == 0) {
    		requestLocationUpdate();
    	}
		
		//chmod for buxybox
		if(isEngBinary) {
			ProcessBuilder exec_chmod = new ProcessBuilder("/system/bin/chmod", "777", "/system/bin/busybox");
			try {
				Process process = exec_chmod.start();
				process.waitFor();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		isActivityActive = true;
	}
	
	@Override
	protected void onPause() {
		super.onPause();
		
		if(getBoolean_pref(pref_CALLLOG_ONGOING) && getInt_pref(pref_LOCATION_REFRESHING_TIME) == 0) {
    		removeLocationUpdate();
    	}
		isActivityActive = false;
	}
	
	public void updateCheckboxStatus() {
		ChangeCheckboxStatus(enable_checkbox, isLogEnabled);
		ChangeCheckboxStatus(pcap_checkbox, getBoolean_pref(pref_CALLLOG_ONGOING));
		ChangeCheckboxStatus(ddms_log_checkbox, getBoolean_pref(pref_DDMS_CHECKED));
		ChangeCheckboxStatus(remove_buffer_checkbox, getBoolean_pref(pref_REMOVE_BUFFER_CHECKED));
		ChangeCheckboxStatus(udp_checkbox, getBoolean_pref(pref_UDP_CHECKED));
		ChangeCheckboxStatus(radio_log_checkbox, getBoolean_pref(pref_RADIO_CHECKED));
		ChangeCheckboxStatus(pcap_log_checkbox, getBoolean_pref(pref_PCAP_CHECKED));
		ChangeCheckboxStatus(use_gps_checkbox, getBoolean_pref(pref_USE_GPS_CHECKED));
		ChangeCheckboxStatus(use_network_location_checkbox, getBoolean_pref(pref_USE_NETWORK_LOCATION_CHECKED));
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
//		if(!isEngBinary) {
//			menu.add(0, first_MENU, 0, "Add AppLog Checkbox");
//		}
		menu.add(0, second_MENU, 0, "Set default");
		menu.add(0, third_MENU, 0, "Field Test Mode");
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()) {
			case first_MENU:
				setBoolean_pref(pref_USE_APPLOG_IN_USERMODE, !getBoolean_pref(pref_USE_APPLOG_IN_USERMODE));
				finish();
				startActivity(new Intent(this, MainActivity.class));
				break;
			case second_MENU:
				if(!getBoolean_pref(pref_CALLLOG_ONGOING)) {
					mUserSharedPreference.setDefault_pref();
					finish();
					startActivity(new Intent(this, MainActivity.class));
				}else {
					ShowToast("Call log is onging!!", Toast.LENGTH_SHORT);
				}
				break;
			case third_MENU:
				boolean mode_now = getBoolean_pref(pref_IS_FIELDTEST_MODE);
				setBoolean_pref(pref_IS_FIELDTEST_MODE, !mode_now);
				ShowToast("Field Test Mode : " + !mode_now, Toast.LENGTH_SHORT);
				break;
		}
		return super.onOptionsItemSelected(item);
	}
	
    public boolean getBoolean_pref(String pref_string)
    {
    	return mUserSharedPreference.getBoolean_pref(pref_string);
    }
    
    public void setBoolean_pref(String pref_string, boolean _value)
    {
    	mUserSharedPreference.setBoolean_pref(pref_string, _value);
    }
    
    public int getInt_pref(String pref_string)
    {
    	return mUserSharedPreference.getInt_pref(pref_string);
    }
    
    public void setInt_pref(String pref_string, int _value)
    {
    	mUserSharedPreference.setInt_pref(pref_string, _value);
    }
    
    public void ChangeCheckboxStatus(CheckBox checkbox, boolean status) {
    	if(checkbox.equals(pcap_checkbox)) {
    		isLogEnabled_applog = status;
    	}
    	checkbox.setChecked(status);
    }
    
    public void ChangeNotification(String who, boolean status) {
    	if(status) {
    		if(who.equals(CALL_LOG)) {
    			showNotificiation("Saving Logs 'Call start ~ Call end'", R.drawable.emo_im_cool);
        	} if(who.equals(APP_LOG)) {
        		showNotificiation("Saving Logs now!", R.drawable.emo_im_laughing);
        	}
    	} else if (pcap_checkbox == null || !pcap_checkbox.isChecked()){
    		removeNotification();
    	}
    }
    
    public void CopyFileToSDcard(int ResourceID, String targetFolder, String targetFileName) {
    	File file = new File(String.format(targetFolder + targetFileName));
    	if(!file.exists()) {
    		Log.d(LOG_TAG, "Make log > Copy to " + targetFolder + targetFileName);
    		ProcessBuilder exec_chmod = new ProcessBuilder("/system/bin/chmod", "777", targetFolder);
    		//ProcessBuilder exec_chmod = new ProcessBuilder("/system/bin/mount", "-o", "remount,rw", "/system");
    		
    		try {
				Process process_chmod = exec_chmod.start();
				process_chmod.waitFor();
			} catch (IOException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
    		Resources resources = getResources();
    		byte [] buffer = new byte[8*1024];
    		int length =0;
    		InputStream is = resources.openRawResource(ResourceID);
    		BufferedInputStream bis = new BufferedInputStream(is);
    		FileOutputStream fos;
			try {
				fos = new FileOutputStream(targetFolder + targetFileName);
				while ((length = bis.read(buffer)) >= 0) fos.write(buffer, 0, length);
	    		fos.flush();
	    		fos.close();
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
    	}
    }
    
    public void ShowToast(String string, int time) {
		if(m_Toast != null) {     
			m_Toast.setText(string); 
			m_Toast.show();
		}else {
			m_Toast = Toast.makeText(getApplicationContext(), string, time);
			m_Toast.show();
		}
    }
    
    private boolean reNameFile(File file, File new_name) {
    	if(file!=null && file.exists() && file.renameTo(new_name)) {
    		return true;
    	} else {
    		return false;
    	}
    }
    
    public void showNotificiation(String text, int icon) {
    	Intent mintent = new Intent(MainActivity.this, IconService.class);
    	mintent.putExtra("text", text);
    	mintent.putExtra("icon", icon);
    	startService(mintent);
    }
    
    public void removeNotification() {
    	stopService(new Intent(MainActivity.this, IconService.class));
    }
    
    public void startLogProcess() {
    	Intent mintent = new Intent(MainActivity.this, ProcessService.class);
    	startService(mintent);
    }
    
    public void killLogprocess() {
    	stopService(new Intent(MainActivity.this, ProcessService.class));
    }
    
    public void requestLocationUpdate() {
    	if(getBoolean_pref(pref_USE_GPS_CHECKED) || getBoolean_pref(pref_USE_NETWORK_LOCATION_CHECKED)) {
    		Intent mintent = new Intent(MainActivity.this, LogLocationService.class);
        	mintent.putExtra("gps", getBoolean_pref(pref_USE_GPS_CHECKED));
        	mintent.putExtra("network", getBoolean_pref(pref_USE_NETWORK_LOCATION_CHECKED));
        	mintent.putExtra("refreshingTime", getInt_pref(pref_LOCATION_REFRESHING_TIME));
        	startService(mintent);
    	}
    }
    
    public void removeLocationUpdate() {
    	if(getBoolean_pref(pref_USE_GPS_CHECKED) || getBoolean_pref(pref_USE_NETWORK_LOCATION_CHECKED)) {
    		stopService(new Intent(MainActivity.this, LogLocationService.class));
    	}
    }
}